package com.example.demo.config;
/* @Author      zouzh
 * @PackageName interceptor-demo
 * @Package     com.example.demo.config
 * @Date        2023/8/25 20:05
 */


import com.example.demo.common.ResultJAjax;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 统一返回值的保底实现类
 */
@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * true ->  才会调用 beforeBodyWrite 方法
     * false -> 永远不不会调用 beforeBodyWrite 方法
     * @param returnType
     * @param converterType
     * @return
     */
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType,
                                  MediaType selectedContentType,
                                  Class selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        // 已经包装好的对象
        if (body instanceof ResultJAjax){
            return body;
        }
        // 对字符串进行判断和处理
        if (body instanceof String){
            ResultJAjax resultJAjax = ResultJAjax.succ(body);
            try {
                return objectMapper.writeValueAsString(resultJAjax);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        return ResultJAjax.succ(body);
    }
}
